package cc.linker.steplink.crm.controller;

import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.MD5;
import cc.linker.steplink.crm.merchanth5.commons.UserInfoUtil;
import cc.linker.steplink.crm.domain.Customer;
import cc.linker.steplink.crm.domain.User;
import cc.linker.steplink.crm.merchant.service.WxService;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchanth5.dao.MaiBaoLaDao;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.redis.CustomerCacheService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.IUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * SCRM 后台用户登录
 */
@Controller
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private WxService wxService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoUtil userInfoUtil;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private CustomerCacheService customerCacheService;

    /**
     * 登录
     * 此接口被CAS过滤
     *
     * @return
     */
    @RequestMapping("/login")
    public String login( HttpServletRequest request,
                        @RequestParam(defaultValue = "info") String weburl) throws GlobalException {
        String usercode = request.getRemoteUser();
        if (!StringUtils.isEmpty(usercode)) {
            User user = userService.getSimpleUser(usercode);
            if (user == null) {
                throw GlobalException.build("用户暂未同步至StepLink_CRM");
            }
            // 关键信息设置
            // 机构支付模式1：微信，2：通联
            Integer payMode = userService.getPayMode(user.getOrgId());
            if (payMode == null) {
                // 从管理中心获取当前机构的支付模式 记录入库
                payMode = userService.getPayModeByUserCenter(user.getOrgId());
                userService.savePayModeByOrgId(user.getOrgId(), payMode);
            }
            Map<String, String> customerMap = userService.isSaler(user.getAdminId());
            String token = this.wxService.getToken(user.getOrgId());

            Boolean isSales = customerMap != null;
            PcUserInfo pcUserInfo = PcUserInfo.builder()
                    .adminCode(usercode)
                    .headSculpture(user.getHeadSculpture())
                    .adminId(user.getAdminId())
                    .orgId(user.getOrgId())
                    .adminName(user.getAdminName())
                    .payMode(payMode)
                    .saler(customerMap != null)
                    .customerId(customerMap != null ? customerMap.get("customerId") : "")
                    .bindPhone(customerMap != null ? customerMap.get("bindPhone") : "")
                    .token(token)
                    .openId(customerMap != null && customerMap.containsKey("openId") ? customerMap.get("openId") : "")
                    .build();

            String storeName = "";
            String storePhone = "";
            Map<String, Object> storeInfo = this.customerCacheService.getCustomerCacheStoreInfo(user.getOrgId(), isSales ? pcUserInfo.getCustomerId() : user.getOrgId(), isSales ? "2" : "1");
            if (storeInfo != null) {
                storeName = storeInfo.containsKey("storeName") && storeInfo.get("storeName") != null ? storeInfo.get("storeName").toString() : "";
                storePhone = storeInfo.containsKey("phone") && storeInfo.get("phone") != null ? storeInfo.get("phone").toString() : "";
            }
            pcUserInfo.setStoreName(storeName);
            pcUserInfo.setStorePhone(storePhone);
//            String key = MD5.encode(request.getSession().getId());
            String key = MD5.encode(usercode);
            this.stringRedisTemplate.opsForValue().set(UserInfoUtil.PCUSERINFO + key, JSON.toJSONString(pcUserInfo, SerializerFeature.WriteMapNullValue), 1, TimeUnit.HOURS);
            // 初始化数据
            userService.setInitialize(user);
            if (weburl.indexOf("?") > -1) {
                String startUrl = weburl.substring(0, weburl.indexOf("?") + 1);
                String endUrl = weburl.substring(weburl.indexOf("?") + 1);
                weburl = startUrl + "ht=" + key + "&orgId=" + user.getOrgId() + "&" + endUrl;
            } else {
                weburl += "?ht=" + key + "&orgId=" + user.getOrgId();
            }
            return "redirect:" + weburl;
        }
        throw GlobalException.build("登录失败");
    }

    /**
     * 获取用户基础信息
     *
     * @return
     */
    @RequestMapping("/info")
    @ResponseBody
    public User info(HttpServletRequest request) throws GlobalException {
        PcUserInfo userinfo = this.userInfoUtil.getPcUserInfo(request);
        String usercode = userinfo.getAdminCode();
        if (StringUtils.isEmpty(usercode)) {
            return null;
        }
        User user = userService.getSimpleUser(usercode);
        if (user == null) {
            throw GlobalException.build("用户暂未同步至StepLink_CRM");
        }
        // 判断是否为小b（小b机构账户在h5端创建）
        boolean isSaler = userinfo.getSaler();
        user.setSaler(isSaler);
        // 支付模式
        Integer payMode = userinfo.getPayMode();
        user.setPayMode(payMode);
        user.setToken(userinfo.getToken());
        String headSculpture = user.getHeadSculpture();
        if (!StringUtils.isEmpty(headSculpture)) {
            String s = systemProperties.getAvatarAddress() + headSculpture;
            user.setHeadSculpture(s);
        }
        if (isSaler) {
            String customerId = merchantInfoService.getCustomerIdByAdminId(user.getAdminId());
            user.setCustomerId(customerId);
        }
        // 江苏台
        boolean jsStation = systemProperties.isJsStation();
        user.setJsStation(jsStation);
        // dong
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("orgcode", user.getOrgId());
            params.put("sysid", systemProperties.getDongSysId());
            Object result = wxService.callUserCenter(params, "/right/orgsyscheck", 1);
            Map resultMap = (Map) result;
            Integer isauth = (Integer) resultMap.get("isauth");
            if (isauth == 1) {
                user.setDong(true);
            }
        } catch (Exception ignored) {

        }
        // app
        boolean isApp = userService.isApp(user.getOrgId());
        user.setApp(isApp);
        return user;
    }

    @ResponseBody
    @GetMapping("/ifSales")
    public Object ifSales(String userId) throws GlobalException {
        if (StringUtils.isEmpty(userId)) {
            throw GlobalException.build("userId不能为空");
        }
        Map<String, String> customerMap = userService.isSaler(userId);
        return customerMap != null;
    }

    /**
     * 获取用户详情接口-对外开放
     */
    @ResponseBody
    @PostMapping("/getUserInfo")
    public Customer getUserInfo(@RequestBody Map<String, Object> param) {
        return userService.getUserInfo(param);
    }

    /**
     * 获取用户列表接口-对外开放UserInfoUtil
     *
     */
    @ResponseBody
    @PostMapping("/getUserPageList")
    public PageInfo getUserPageList(@RequestBody Map<String, Object> param) {
        return userService.getUserPageList(param);
    }

    /**
     * 获取用户行为-对外开放
     * type
     * 1 动态 2 积分动态 3 idp动态 4 文章动态
     * actionType
     * 1 变更负责人 2 编辑 3 备注 4 购物 5 打开链接 6 手动积分 7 文章点赞积分 8 文章转发积分 9 文章评论积分 10 对话 11 关注
     * 12 h5访问 13 客服会话 14 打开文章 15 阅读全文 16 查看个人主页 17 关注公众号 18 一次性订阅 19 评论 20 点赞 21 阅读停留时长 22 点击活动
     *
     *  pageIndex  页码
     *  pageSize   页大小
     *  customerId 用户id
     *  createTime 行为时间（选填）,例”2020-1-13”
     * @ token      oauth的access_token（必填）
     */
    @ResponseBody
    @PostMapping("/getUserBehaviorList")
    public PageInfo getUserBehaviorList(@RequestBody Map<String, Object> param) {
        return userService.getUserBehaviorList(param);
    }

    /**
     * 支付宝用户接入-对外开放
     *
     * @param : nickName 昵称
     * @param : userCode  机构帐号
     * @param : alipayId 支付宝唯一标识
     */
    @ResponseBody
    @PostMapping("/alipayUserSave")
    public void alipayUserSave(@RequestBody Map<String, Object> param) {
        userService.alipayUserSave(param);
    }

    /**
     * app用户接入-对外开放
     *
     * @param : nickName 昵称
     * @param : userCode  机构帐号
     * @param : alipayId 支付宝唯一标识
     */
    @ResponseBody
    @PostMapping("/appUserSave")
    public void appUserSave(@RequestBody Map<String, Object> param) {
        userService.appUserSave(param);
    }
}
